#include "medicineupdate.h"
#include "ui_medicineupdate.h"
#include <QMessageBox>

MedicineUpdateWindow::MedicineUpdateWindow(QWidget *parent)
    : QWidget(parent)
    , medicineupdatewindowUi(new Ui::MedicineUpdateWindow)
    , networkManager(new NetworkManager(this))
{
    medicineupdatewindowUi->setupUi(this);

    connect(networkManager, &NetworkManager::editMedicineResponseReceived, this, &MedicineUpdateWindow::handleUpdateMedicineResponse);
}

MedicineUpdateWindow::~MedicineUpdateWindow()
{
    delete medicineupdatewindowUi;
}

void MedicineUpdateWindow::on_updateButton_clicked()
{
    int id = medicineupdatewindowUi->idLineEdit->text().toInt();
    QString name = medicineupdatewindowUi->nameLineEdit->text();
    QString category = medicineupdatewindowUi->categoryLineEdit->text();
    QString supplier = medicineupdatewindowUi->supplierLineEdit->text();
    double price = medicineupdatewindowUi->priceLineEdit->text().toDouble();
    int stock = medicineupdatewindowUi->stockLineEdit->text().toInt();
    int threshold = medicineupdatewindowUi->thresholdLineEdit->text().toInt();
    int validity = medicineupdatewindowUi->validityLineEdit->text().toInt();

    if (name.isEmpty() || category.isEmpty() || supplier.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请填写所有必填字段。");
        return;
    }

    QJsonObject medicineInfo;
    medicineInfo["id"] = id;
    medicineInfo["name"] = name;
    medicineInfo["category"] = category;
    medicineInfo["supplier"] = supplier;
    medicineInfo["price"] = price;
    medicineInfo["stock"] = stock;
    medicineInfo["threshold"] = threshold;
    medicineInfo["validity"] = validity;

    networkManager->editMedicine(medicineInfo);
}

void MedicineUpdateWindow::on_resetButton_clicked()
{
    medicineupdatewindowUi->nameLineEdit->clear();
    medicineupdatewindowUi->categoryLineEdit->clear();
    medicineupdatewindowUi->supplierLineEdit->clear();
    medicineupdatewindowUi->priceLineEdit->clear();
    medicineupdatewindowUi->stockLineEdit->clear();
    medicineupdatewindowUi->thresholdLineEdit->clear();
    medicineupdatewindowUi->validityLineEdit->clear();
}

void MedicineUpdateWindow::handleUpdateMedicineResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {
        QMessageBox::information(this, "成功", "药品更新成功！");
        on_resetButton_clicked();
    } else {
        QMessageBox::warning(this, "错误", "药品更新失败：" + desc);
    }
}
